import requests
from bs4 import BeautifulSoup
import re
import pypinyin
import urllib.request
import urllib3
import time
def hp(word):    
    s = ''    
    for i in pypinyin.pinyin(word, 
            style=pypinyin.NORMAL):     
        s += ''.join(i)    
    return s

def get_weather(city):
    headers = {'User-Agent': 'Mozilla/(Windows NT 10.0; WOW64) AppleWebKit/537.3(KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36','Host': 'www.tianqi.com'}
    link = 'https://www.tianqi.com/'+city+'/'
    r = requests.get(link, headers=headers) 
    r.encoding = r.apparent_encoding
    soup = BeautifulSoup(r.text, "html.parser")
    renow = r'<p class="now"><b>(.[^&]*?)</b><i>℃</i></p>'
    nowweather = re.findall(renow,r.text)
    retodayweather = r'<span><b>(.[^&]*?)</b>(.[^&]*?)</span>'
    temp = soup.find_all('dd',class_='weather')
    todayweather = re.findall(retodayweather,str(temp))
    retodashidu = r'<dd class="shidu"><b>(.[^&]*?)</b><b>(.[^&]*?)</b><b>(.[^&]*?)</b></dd>'
    shidu = soup.find_all('dd',class_='shidu')
    todayshidu = re.findall(retodashidu,str(shidu))
    rekongqi = r'<dd class="kongqi"><h5 style="(.[^&]*?)">(.[^&]*?)</h5><h6>(.[^&]*?)</h6><span>(.[^&]*?)<br/>(.[^&]*?)</span></dd>'
    kongqi = soup.find_all('dd',class_='kongqi')
    todaykongqi = re.findall(rekongqi, str(kongqi))
    weather = ('当前温度:%s℃\n今天天气:%s\t%s\n%s\n%s\n%s\n%s\n%s\n%s    %s'%(nowweather[0],todayweather[0][0],todayweather[0][1],todayshidu[0][0],todayshidu[0][1],todayshidu[0][2],todaykongqi[0][1],todaykongqi[0][2],todaykongqi[0][3],todaykongqi[0][4]))
    print(soup.find_all('小雨'))
    return weather
print(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))
print(time.strftime('%M',time.localtime(time.time())))
chengshi = input("请输入城市：")
if chengshi == '新都':
    print(get_weather('xindu'))
else:
    city = hp(chengshi)
    print(get_weather(city))
